<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/8
 * Time: 17:41
 */

namespace app\applet\model;


use think\Db;
use think\Exception;
use WeixinPay\WeixinPay;
class MemberTransfer
{

    public function score($input){
        $asset=Db::name("member_asset")->where(['member_id'=>$input['member_id']])->field("score,coin")->find();
        $info['mem_score']=$asset['score'];
        return $info;
    }

    public function coin($input){
        $asset=Db::name("member_asset")->where(['member_id'=>$input['member_id']])->field("score,coin")->find();

        $info['mem_coin']=$asset['coin'];
        return $info;
    }

    public function getRealName($input){
        $mobile=trim($input['mobile']);
        $member_id=Db::name("member")->where(['mobile'=>$mobile])->value("member_id");
        if($member_id<=0){
            returnJson(-2004,'当前手机号用户不存在');
        }
        $memberInfo=Db::name("member_info")->where(['member_id'=>$member_id])->field('status,real_name')->find();

        if( $memberInfo['status']==0){
            returnJson(-2003,'收款人还未实名认证，无法进行信息核实');
        }elseif( $memberInfo['status']==2) {
            returnJson(-2003,'收款人实名认证审核中，无法进行信息核实');
        }elseif( $memberInfo['status']==3){
            returnJson(-2003,'收款人实名认证审核失败，无法进行信息核实');
        }
        $info=[];
        $info['real_name'] = $memberInfo['real_name'];
        return $info;

    }


    /**
     * @param $input
     * 转积分记录订单生成
     */
    public function transferScore($input){
       if($input['score_num']<=0){
           returnJson(-2003,'发放额度错误');
       }
       //获取会员当前积分
       $score=Db::name("member_asset")->where(['member_id'=>$input['member_id']])->value("score");
       if($input['score_num']>$score){
           returnJson(-2003,'用户积分额度不足');
       }
        //获取收账人信息
        $receive_id=Db::name("member")->where(['mobile'=>$input['receive_mobile']])->value("member_id");
        if(empty($receive_id)){
            returnJson(-2003,'收款人不存在，请核对信息');
        }
        if($receive_id==$input['member_id']){
            returnJson(-2003,'自己不能转给自己');
        }
        //姓名判断
        $receiverInfo=Db::name("member_info")
            ->where(['member_id'=>$receive_id])->field("status,real_name")->find();
        if($receiverInfo['status']==0){
            returnJson(-2003,'收款人还未实名认证，无法进行信息核实');
        }elseif($receiverInfo['status']==2) {
            returnJson(-2003,'收款人实名认证审核中，无法进行信息核实');
        }elseif($receiverInfo['status']==3){
            returnJson(-2003,'收款人实名认证审核失败，无法进行信息核实');
        }

        if($receiverInfo['real_name']!=$input['receive_name']){
            returnJson(-2003,'收币人信息错误，请核对信息');
        }
        $trans_type=$input['trans_type'];
        if($trans_type==2){
            $nums=Db::name("member_transfer")
                ->where(['member_id'=>$input['member_id'],'status'=>1,'trans_type'=>2])->count();
            if($nums>0){
                returnJson(-2003,'有未完成的担保转账');
            }
        }
        //生成订单记录
        Db::startTrans();
        try{

            $tm=time();
            $trans_sn=$tm.mt_rand(10000,99999);
            $score_money= $input['score_num']-0.01;

            $data=['member_id'=>$input['member_id'],'type'=>1,"receive_id"=>$receive_id,
                'trans_sn'=>$trans_sn,"receive_mobile"=>$input['receive_mobile'],
                "receive_name"=>$input['receive_name'],'trans_type'=>$trans_type,
                'transfer_num'=>$input['score_num'],'pay_num'=>$score_money,
                'wx_pay_num'=>0.01,'status'=>1,'create_time'=>$tm];

            $transferId=Db::name("member_transfer")->insertGetId( $data);

            if( $transferId<=0){
                throw  new Exception("操作失败");
            }
            if($score_money>0){
                $num=Db::name("member_asset_log")
                    ->insert(['member_id'=>$input['member_id'],'type'=>3,'amount'=>$score_money,
                        'source_type'=>2,'description'=>'商城待支付','change_type'=>1,'log_type_id'=>55,
                        'relation_id'=>$transferId,'create_time'=>$tm]);
                if($num<=0){
                    throw  new Exception("操作失败");
                }
            }


            if( $trans_type==1){//直接转账
                $sql="update mm_member_asset set score=score-$score_money,frozen_score=frozen_score+$score_money,
pay_frozen_score=pay_frozen_score+$score_money where member_id=".$input['member_id']." and score>=$score_money  ";
                $num=Db::query($sql);
                if($num<=0){
                    throw  new Exception("操作失败");
                }
                $rst=$this->orderPay($trans_sn,2,$input['member_id']);
            }elseif($trans_type==2){//担保转账
                $sql="update mm_member_asset set score=score-$score_money,score_trans_frozen=score_trans_frozen+$score_money,
frozen_score=frozen_score+$score_money,pay_frozen_score=pay_frozen_score+$score_money where 
member_id=".$input['member_id']." and score>=$score_money  ";
                $num=Db::query($sql);
                if($num<=0){
                    throw  new Exception("操作失败");
                }
            }

            $rst['transferId']=$transferId;
            $rst['trans_sn']=$trans_sn;
            Db::commit();
            return $rst;
        }catch (Exception $e){
            Db::rollback();
            returnJson(-2004,'系统繁忙');
        }

    }
    /**
     * @param $input
     * 转金币记录订单生成
     */
    public function transferCoin($input){
        if($input['coin_num']<=0){
            returnJson(-2003,'发放额度错误');
        }
        //获取会员当前金币数量
        $coin=Db::name("member_asset")->where(['member_id'=>$input['member_id']])->value("coin");
        if($input['coin_num']>$coin){
            returnJson(-2003,'用户金币额度不足');
        }
        //获取收账人信息

        $receive_id=Db::name("member")->where(['mobile'=>$input['receive_mobile']])->value("member_id");
        if(empty($receive_id)){
            returnJson(-2003,'收币人不存在，请核对信息');
        }
        if($receive_id==$input['member_id']){
            returnJson(-2003,'自己不能转给自己');
        }
        //姓名判断
        $receiverInfo=Db::name("member_info")->where(['member_id'=>$receive_id])->field("status,real_name")->find();
        if($receiverInfo['status']==0){
            returnJson(-2003,'收币人还未实名认证，无法进行信息核实');
        }elseif($receiverInfo['status']==2) {
            returnJson(-2003,'收币人实名认证审核中，无法进行信息核实');
        }elseif($receiverInfo['status']==3){
            returnJson(-2003,'收币人实名认证审核失败，无法进行信息核实');
        }

        if($receiverInfo['real_name']!=$input['receive_name']){
            returnJson(-2003,'收币人信息错误，请核对信息');
        }
        Db::startTrans();
        try {
            $tm=time();
            $trans_sn=$tm.mt_rand(10000,99999);
            $coin_money= $input['coin_num']-0.01;
            $data=['member_id'=>$input['member_id'],'type'=>2,'trans_sn'=>$trans_sn,"receive_id"=>$receive_id,
                "receive_mobile"=>$input['receive_mobile'],
                "receive_name"=>$input['receive_name'],'transfer_num'=>$input['coin_num'],
                'pay_num'=>$coin_money,'wx_pay_num'=>0.01,'status'=>1,'create_time'=>$tm];
            $transferId=Db::name("member_transfer")->insertGetId( $data);
             if($transferId<=0){
                 throw  new Exception("操作失败");
             }
            if($coin_money>0){
                $num=Db::name("member_asset_log")
                    ->insert(['member_id'=>$input['member_id'],'type'=>3,'amount'=>$coin_money,
                        'source_type'=>2,'description'=>'商城待支付','change_type'=>2,'log_type_id'=>56,
                        'relation_id'=>$transferId,'create_time'=>$tm]);
                if($num<=0){
                    throw  new Exception("操作失败");
                }
            }
            $sql="update mm_member_asset set coin=coin-$coin_money,frozen_coin=frozen_coin+$coin_money where 
member_id=".$input['member_id']."  and coin>=$coin_money ";
            $num=Db::query($sql);
            if($num<=0){
                throw  new Exception("操作失败");
            }
            $rst=$this->orderPay($trans_sn,2,$input['member_id']);
            $rst['transferId']=$transferId;
            $rst['trans_sn']=$trans_sn;
            Db::commit();
            return $rst;
        }catch (Exception $e){
            Db::rollback();
            returnJson(-2004,'系统繁忙');
        }


    }

    /**
     * 取消支付
     */
    public function cancelOrder($input){

        $order_sn=$input['trans_sn'];
        $member_id=$input['member_id'];
        //获取当前记录
        $payInfo=Db::name("member_transfer")->where(['member_id'=>$member_id,"trans_sn"=>$order_sn,'status'=>['not in',[2,3]]])->field("trans_id,pay_num,type,trans_type")->find();
        $score_trans_frozen=0;

        if( $payInfo['type']==1){

            $coin_money= 0;
            $score_money= $payInfo['pay_num'];
            if($payInfo['trans_type']==2){//担保转账

                $score_trans_frozen=$payInfo['pay_num'];
            }
        }elseif( $payInfo['type']==2){
            $coin_money= $payInfo['pay_num'];
            $score_money= 0;
        }
        $transID= $payInfo['trans_id'];
        Db::startTrans();
        try {
            if($coin_money>0||$score_money>0){
                $sql="update mm_member_asset set score=score+$score_money,frozen_score=frozen_score-$score_money,score_trans_frozen=score_trans_frozen-$score_trans_frozen,pay_frozen_score=pay_frozen_score-$score_money,coin=coin+$coin_money,frozen_coin=frozen_coin-$coin_money where member_id=".$member_id." and frozen_score>=$score_money  and pay_frozen_score>=$score_money and frozen_coin>=$coin_money and score_trans_frozen>=$score_trans_frozen";
                $num=Db::query($sql);
                if($num<=0){
                    throw new Exception("更新失败");
                }
            }
            $num=Db::name("member_transfer")->where(['member_id'=>$member_id,"trans_sn"=>$order_sn])->update(['status'=>3]);
            if($num<=0){
                throw new Exception("更新失败");
            }
            $num=Db::name("member_asset_log")->where(['member_id'=>$member_id,'relation_id'=>$transID,"log_type_id"=>['in',[55,56]]])->delete();
            if($num<=0){
                throw new Exception("更新失败1");
            }
            Db::commit();
            return ['trans_sn'=>$order_sn];
        }catch (Exception $e){

            Db::rollback();

            returnJson(-2004,"操作失败");
        }


    }

    /**
     * 担保转账详情
     */
    public function warrantInfo($member_id){
        $transferInfo=Db::name("member_transfer")->where(['member_id'=>$member_id,'status'=>1,'trans_type'=>2])->find();
        $rst=[];
        if(!empty( $transferInfo)){
            $order_sn=$transferInfo['trans_sn'];
            $type=1;
            $rst=$this->orderPay($order_sn,$type,$member_id);
            $rst['trans_sn'] =$transferInfo['trans_sn']  ;
            $rst['receive_mobile'] =$transferInfo['receive_mobile']  ;
            $rst['receive_name'] =$transferInfo['receive_name']  ;
        }
        return $rst;

    }


    /**
     * 微信支付
     */
    public function orderPay($order_sn,$type,$member_id){
        #获取openid
        $openid = Db::name("member")
            ->field("openid")
            ->where(['member_id'=>$member_id])
            ->value("openid");
        //$total_fee=1;
        $total_fee=0.01;
        if($type==1){
            $body = "积分转账";
        }elseif($type==2){
            $body = "金币转账";
        }

        $notify_url =  request()->domain()."/index.php/applet/Notify/transferPayment";

        #调取支付接口
        $weixinPay = new WeixinPay($openid, $body, $total_fee, $order_sn,$notify_url);
        // 发起微信支付
        $result = $weixinPay->pay();
        return $result;
    }

}

